package com.mdd.admin.service.jiaz.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.IDistributionApplyService;
import com.mdd.admin.service.jiaz.IEngineerApplyService;

import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.EngineerApply;
import com.mdd.common.entity.distribution.DistributionApply;
import com.mdd.common.enums.EngineerEnum;
import com.mdd.common.mapper.engineer.EngineerApplyMapper;
import com.mdd.common.mapper.engineer.EngineerMapper;
import com.mdd.common.service.EngineerService;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.UrlUtils;
import com.mdd.common.validate.engineer.EngineerApplyAuditValidate;
import com.mdd.common.validate.engineer.EngineerApplySearchValidate;
import com.mdd.common.vo.engineer.EngineerApplyAdDetailVo;
import com.mdd.common.vo.engineer.EngineerApplyListedVo;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class EngineerApplyServiceImpl implements IEngineerApplyService {

    @Resource
    EngineerApplyMapper engineerApplyMapper;

    @Resource
    IDistributionApplyService distributionApplyService;

    @Resource
    EngineerMapper engineerMapper;

    @Resource
    EngineerService engineerService;

    @Override
    public PageResult<EngineerApplyListedVo> list(PageValidate pageValidate, EngineerApplySearchValidate searchValidate) {

        Integer pageNo = pageValidate.getPageNo();
        Integer pageSize = pageValidate.getPageSize();
        Integer applyStatus = searchValidate.getStatus();
        String userKeyword = searchValidate.getSearchUserKeyword();
        String inviterKeyword = searchValidate.getSearchInviterKeyword();

        MPJQueryWrapper<EngineerApply> mpjQueryWrapper = new MPJQueryWrapper<>();
        mpjQueryWrapper
                .orderByDesc("t.id")
                .eq("t.is_delete", 0)
                .leftJoin("?_user U1 ON t.user_id=U1.id".replace("?_", GlobalConfig.tablePrefix))
                .leftJoin("?_user U2 ON U1.inviter_id=U2.id".replace("?_", GlobalConfig.tablePrefix));

        // 用户搜索
        if (StringUtils.isNotBlank(userKeyword)) {
            mpjQueryWrapper.nested(wq -> wq
                    .like("U1.sn", userKeyword).or()
                    .like("U1.nickname", userKeyword).or()
                    .like("U1.mobile", userKeyword));
        }

        // 邀请人信息
        if (StringUtils.isNotBlank(inviterKeyword)) {
            mpjQueryWrapper.nested(wq -> wq
                    .like("U2.sn", inviterKeyword).or()
                    .like("U2.nickname", inviterKeyword).or()
                    .like("U2.mobile", inviterKeyword));
        }

        // 申请时间
        engineerApplyMapper.setSearch(mpjQueryWrapper, searchValidate, new String[]{
                "datetime:startTime-endTime@t.create_time:str"
        });

        Map<String, Object> extend = new LinkedHashMap<>();
        MPJQueryWrapper<EngineerApply> allMpj = mpjQueryWrapper.clone();
        MPJQueryWrapper<EngineerApply> waitMpj = mpjQueryWrapper.clone();
        MPJQueryWrapper<EngineerApply> passMpj = mpjQueryWrapper.clone();
        MPJQueryWrapper<EngineerApply> refuseMpj = mpjQueryWrapper.clone();
        extend.put("all", engineerApplyMapper.selectCount(allMpj.select("t.id")));
        extend.put("wait", engineerApplyMapper.selectCount(waitMpj.select("t.id").eq("t.status", EngineerEnum.APPLY_STATUS_ING.getCode())));
        extend.put("pass", engineerApplyMapper.selectCount(passMpj.select("t.id").eq("t.status", EngineerEnum.APPLY_STATUS_SUCCESS.getCode())));
        extend.put("refuse", engineerApplyMapper.selectCount(refuseMpj.select("t.id").eq("t.status", EngineerEnum.APPLY_STATUS_FAIL.getCode())));

        // 申请状态
        if (StringUtils.isNotNull(applyStatus) && applyStatus > 0) {
            mpjQueryWrapper.eq("t.status", applyStatus);
        }

        mpjQueryWrapper
                .selectAll(EngineerApply.class)
                .select("U1.sn,U1.nickname,U1.avatar, U1.inviter_id")
                .select("U2.nickname as inviter_name");

        IPage<EngineerApplyListedVo> iPage = engineerApplyMapper.selectJoinPage(
                new Page<>(pageNo, pageSize),
                EngineerApplyListedVo.class,
                mpjQueryWrapper);

        for (EngineerApplyListedVo vo : iPage.getRecords()) {
            vo.setStatusMsg(EngineerEnum.getApplyStatusMsg(vo.getStatus()));
            vo.setAvatar(UrlUtils.toAbsoluteUrl(vo.getAvatar()));
            vo.setCreateTime(TimeUtils.timestampToDate(vo.getCreateTime()));
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords(), extend);
    }

    @Override
    public EngineerApplyAdDetailVo detail(Integer id) {
        EngineerApplyAdDetailVo vo = engineerApplyMapper.selectJoinOne(
                EngineerApplyAdDetailVo.class,
                new MPJQueryWrapper<DistributionApply>()
                        .eq("t.is_delete", 0)
                        .eq("t.id", id)
                        .selectAll(DistributionApply.class)
                        .select("U1.sn,U1.nickname,U1.avatar,U2.nickname as inviter")
                        .leftJoin("?_user U1 ON t.user_id=U1.id".replace("?_", GlobalConfig.tablePrefix))
                        .leftJoin("?_user U2 ON U1.inviter_id=U2.id".replace("?_", GlobalConfig.tablePrefix))
                        .last("limit 1"));

        vo.setStatusMsg(EngineerEnum.getApplyStatusMsg(vo.getStatus()));
        vo.setAvatar(UrlUtils.toAbsoluteUrl(vo.getAvatar()));
        vo.setRegion(distributionApplyService.getRegion(vo.getProvince(), vo.getCity(), vo.getDistrict()));
        vo.setCreateTime(TimeUtils.timestampToDate(vo.getCreateTime()));
        if (StringUtils.isNotEmpty(vo.getAuditTime()) && Long.parseLong(vo.getAuditTime()) > 0) {
            vo.setAuditTime(TimeUtils.timestampToDate(vo.getAuditTime()));
        } else {
            vo.setAuditTime("");
        }
        return vo;
    }

    @Override
    public void audit(EngineerApplyAuditValidate auditValidate) {
        Integer applyId = auditValidate.getId();
        Integer status = auditValidate.getStatus();
        String auditRemark = auditValidate.getAuditRemark();

        // 申请记录
        EngineerApply engineerApply = engineerApplyMapper.selectById(applyId);
        Assert.notNull(engineerApply, "申请信息不存在");

        if (status.equals(1)) {
            engineerApply.setStatus(EngineerEnum.APPLY_STATUS_SUCCESS.getCode());
        } else {
            engineerApply.setStatus(EngineerEnum.APPLY_STATUS_FAIL.getCode());
        }

        // 更新申请记录
        if (StringUtils.isNotBlank(auditRemark)) {
            engineerApply.setAuditRemark(auditRemark);
        }
        engineerApply.setUpdateTime(TimeUtils.timestamp());
        engineerApply.setAuditTime(TimeUtils.timestamp());
        engineerApplyMapper.updateById(engineerApply);

        // 更新用户分销基础信息
        if (status.equals(1)) {
            // 新增分销信息表
            engineerService.addEngineerData(engineerApply.getUserId());
        }
    }

}
